package com.lebang.controller.sys;

import com.alibaba.fastjson.JSONObject;
import com.lebang.common.Login;
import com.lebang.domain.MemberInviteRebateRecord;
import com.lebang.domain.MemberRebateLog;
import com.lebang.domain.MemberRebateTotalmoney;
import com.lebang.entity.RequestHeaders;
import com.lebang.entity.sys.LbbUser;
import com.lebang.example.MemberRebateLogExample;
import com.lebang.mapper.MemberInviteRebateRecordMapper;
import com.lebang.model.MoneyCategory;
import com.lebang.model.Whether;
import com.lebang.model.enums.buss.TaskCategory;
import com.lebang.service.MemberInviteRebateRecordService;
import com.lebang.service.MemberRebateTotalmoneyService;
import com.lebang.service.UserService;
import com.lebang.service.buss.MemberInviteStatisticsService;
import com.lebang.service.buss.MemberTradeService;
import com.lebang.service.sys.DictService;
import com.lebang.service.sys.MemberRebateLogService;
import com.lebangweb.response.Callback;
import com.lebangweb.response.JsonData;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.math.BigDecimal;
import java.time.LocalDateTime;


/**
 * member_rebate_log
 *
 * @author xwj
 * @date 2020-08-06
 */
@Controller
@RequestMapping("/sys/memberrebatelog")
public class MemberRebateLogController {
    @Autowired
    private MemberRebateLogService baseService;
    @Autowired
    private UserService userService;
    @Autowired
    private DictService dictService;
    @Autowired
    private MemberTradeService memberTradeService;
    @Autowired
    private MemberRebateTotalmoneyService memberRebateTotalmoneyService;
    @Autowired
    private MemberInviteStatisticsService memberInviteStatisticsService;
    @Autowired
    private MemberInviteRebateRecordService memberInviteRebateRecordService;


    @GetMapping("/list")
    public String list() {
        return "/memberrebatelog/list";
    }

    @GetMapping("/add")
    public String add(Long id, Model model) {
        MemberRebateLog vo;
        if (id != null) {
            vo = baseService.selectById(id);
        } else {
            vo = new MemberRebateLog();
        }
        model.addAttribute("item", vo);
        return "/memberrebatelog/edit";
    }


    @PostMapping("/edit")
    @ResponseBody
    public JsonData edit(MemberRebateLog vo, HttpSession session) {
        String userid = (String) session.getAttribute("userid");
        LbbUser lbbUser = userService.get(userid);
        if(!lbbUser.getUsername().equals("hwq")){
            return Callback.fail("fail", "沒有权限");
        }

            vo.setCreateTime(LocalDateTime.now());
            //徒弟的返利百分比
            int mas = dictService.selectIntByKeyName("sf_rebate");
            vo.setRebateRate(mas);
            vo.setAmount(new BigDecimal(vo.getMoney()).divide(new BigDecimal(100), 2, BigDecimal.ROUND_DOWN).multiply(new BigDecimal(mas)).divide(new BigDecimal(100), 2, BigDecimal.ROUND_DOWN));
            int masterMoney = vo.getAmount().multiply(new BigDecimal(100)).intValue();
            MemberRebateTotalmoney memberRebateTotalmoney = memberRebateTotalmoneyService.selectById(vo.getMemberId());
            int de = 0;
            int mo = 0;
            mo = dictService.selectIntByKeyName("td_max") * 100;
            if (memberRebateTotalmoney.getTotalMoney()<= mo) {
                if (memberRebateTotalmoney.getTotalMoney()+ masterMoney >= mo) {
                    //计算当类型为0或1时相对应返利值
                    de = mo - memberRebateTotalmoney.getTotalMoney();
                    if (de > 0) {
                        de = mo -memberRebateTotalmoney.getTotalMoney();
                    } else {
                        return Callback.fail("fail", "返利超过最大限制");
                    }
                } else {
                    de = masterMoney;
                }
            }
//            memberTradeService.addMoney(vo.getInviteId(), de,
//                    "徒弟赚钱返利",
//                     "徒弟赚钱返利" ,
//                    "", new RequestHeaders(), "", new MoneyCategory(Whether.NO, TaskCategory.REBATE).notMaster());

            baseService.insertModel(vo);

            //.一个徒弟/徒孙可给师傅带来的最高收益累计/此时id为等级最低的徒孙id
            memberRebateTotalmoneyService.addTotalMoney(vo.getMemberId(), 0, de);
            //计入累计收益
            memberInviteStatisticsService.addTotalAmount(vo.getInviteId(), de, 0);
            //师徒收益存入redis
            memberInviteRebateRecordService.settoday(vo.getInviteId(), de);

            MemberInviteRebateRecord rebateRecord = new MemberInviteRebateRecord();
            rebateRecord.setCreateTime(LocalDateTime.now());
            rebateRecord.setMemberId(vo.getMemberId());
            rebateRecord.setMoney(de);
            rebateRecord.setType(0);
            rebateRecord.setInviteId(vo.getInviteId());
            rebateRecord.setRateRebate(0);
            baseService.insertMemberInviteRebateRecord(rebateRecord);

        return Callback.success("success", "修改成功");
    }

    @Login
    @PostMapping("/delete")
    @ResponseBody
    public JsonData delete(Long id) {
        baseService.deleteById(id);
        return Callback.success("success", "删除成功");
    }

    @ApiOperation(value = "分页")
    @PostMapping("/list")
    @ResponseBody
    public JSONObject list(HttpServletRequest request, @RequestParam Integer page, @RequestParam Integer limit) {
        MemberRebateLogExample example = new MemberRebateLogExample();
        example.setOffset((page - 1) * limit.longValue());
        example.setLimit(limit);
        MemberRebateLogExample.Criteria criteria = example.createCriteria();
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("code", 0);
        jsonObject.put("data", baseService.selectByExample(example));
        jsonObject.put("count", baseService.countByExample(example));
        return jsonObject;
    }
}
